package com.ljx.itbbs.server.user.service.impl;

import com.ljx.itbbs.server.user.dao.UserRoleRelationDao;
import com.ljx.itbbs.server.user.domain.entity.UserRoleRelationEntity;
import com.ljx.itbbs.server.user.domain.vo.req.RoleGiveReq;
import com.ljx.itbbs.server.user.service.UserRoleRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserRoleRelationServiceImpl implements UserRoleRelationService {

    @Autowired
    private UserRoleRelationDao userRoleRelationDao;


    @Override
    public void save(Long id, Long roleId) {
        UserRoleRelationEntity userRoleRelationEntity = buildUserRoleRelation(id, roleId);
        userRoleRelationDao.save(userRoleRelationEntity);
    }

    private UserRoleRelationEntity buildUserRoleRelation(Long id, Long roleId) {
        UserRoleRelationEntity userRoleRelationEntity = new UserRoleRelationEntity();
        userRoleRelationEntity.setRoleId(roleId);
        userRoleRelationEntity.setUserId(id);
        return userRoleRelationEntity;
    }

    @Override
    public void giveUserRole(RoleGiveReq req) {
        // 删除之前的角色
        userRoleRelationDao.deleteByUid(req.getUid());
        // 保存角色
        List<UserRoleRelationEntity> list = req.getRoleList()
                .stream()
                .map(item -> buildUserRoleRelation(req.getUid(), item))
                .collect(Collectors.toList());
        userRoleRelationDao.saveBatch(list);
    }
}
